<!--历史数据/综合数据-->
<template>
  <div class="lc_wrap">
    <el-row class="HistorydataTabel loamHistorydataTabel">

      <!-- 左侧树 -->
      <el-col :span="leftWidth">
        <div class="box treeBox">
          <basic-container>
            <lcTree @ready="ready" :deviceType="3"></lcTree>
          </basic-container>
        </div>
      </el-col>

      <!-- 内容 -->
      <el-col :span="rightWidth" class="table-wrapper">
        <overlay @changeTreeBox="changeTreeBox"></overlay>
        <basic-container>

          <!-- 自定义搜索功能 -->
          <div class="search-tools">
            <div class="search-left" v-if="dateType == 0">
              <el-date-picker
                v-model="dateFrom"
                type="date"
                size="small"
                placeholder="开始日期"
                :picker-options="pickerOption"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
              <div>&nbsp;至&nbsp;</div>
              <el-date-picker
                v-model="dateTo"
                type="date"
                size="small"
                placeholder="结束日期"
                :picker-options="pickerOption"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
              <div>&nbsp;&nbsp;</div>
            </div>
            <div class="search-left" v-else>
              <el-date-picker
                v-model="dateFrom2"
                type="datetime"
                size="small"
                placeholder="开始日期"
                :picker-options="pickerOption"
                value-format="yyyy-MM-dd HH:mm:ss"
                disabled
              ></el-date-picker>
              <div style="color: #ccc;">&nbsp;至&nbsp;</div>
              <el-date-picker
                v-model="dateTo2"
                type="datetime"
                size="small"
                placeholder="结束日期"
                :picker-options="pickerOption"
                value-format="yyyy-MM-dd HH:mm:ss"
                disabled
              ></el-date-picker>
              <div>&nbsp;&nbsp;</div>
            </div>
            <div class="search-right">
              <div class="search-tabs">
                <el-radio
                  v-model="dateType"
                  v-for="(item, index) in dateTypeList"
                  :key="index"
                  :label="item.label"
                  :disabled="item.disable"
                  @change="changeDateType"
                  >{{ item.value }}
                </el-radio>
              </div>
              <div class="searcg-btns">
                <el-button
                  type="primary"
                  size="small"
                  icon="el-icon-search"
                  @click="search"
                  >搜 索</el-button
                >
              </div>
            </div>
          </div>
          <avue-crud
            v-if="isTableShow"
            :option="option"
            :table-loading="loading"
            :data="data"
            :page.sync="page"
            :permission="permissionList"
            v-model="form"
            ref="crud"
            @search-reset="searchReset"
            @current-change="currentChange"
            @size-change="sizeChange"
            @refresh-change="refreshChange"
          >
						<template slot="menuLeft">
							<div class="table-tools"  style="padding: 0;display: inline">
								<el-button type="warning" size="small" plain icon="el-icon-download" @click="handleExport">导出</el-button>
							</div>
						</template>


            <template
              :slot="item.alias"
              slot-scope="scope"
              v-for="(item, index) in factorList"
            >
              <div :key="index" v-html="scope.row[item.alias]"></div>
            </template>
          </avue-crud>
        </basic-container>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { getHead, getList, getDeptTree } from "@/api/loam/historydata";
import { mapGetters } from "vuex";
import { xlsxDownloadExl } from "@/util/exportExcel";
import { dateFormat, getPreDay } from "@/util/date";
import lcTree from "@/components/common/tree.vue";
import overlay from "@/components/common/overlay.vue";
import { getToken } from "@/util/auth";	  // 导出表格的时候用得到
export default {
  components: {
    lcTree,
    overlay
  },
  data() {

    // 定义一个时间格式化函数
    Date.prototype.format = function(format) {
      var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        S: this.getMilliseconds()
      };
      if (/(y+)/.test(format)) {
        format = format.replace(
          RegExp.$1,
          (this.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
      }
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(format)) {
          format = format.replace(
            RegExp.$1,
            RegExp.$1.length == 1
              ? o[k]
              : ("00" + o[k]).substr(("" + o[k]).length)
          );
        }
      }
      return format;
    };

    return {
      dateTypeList: [
        {
          label: 0,
          value: "自定义"
        },
        {
          label: 1,
          value: "24小时"
        },
        {
          label: 2,
          value: "48小时"
        },
        {
          label: 4,
          value: "96小时"
        }
      ],
      dateType: 0,
      dateFrom2: dateFormat(getPreDay(1)),
      dateTo2: dateFormat(new Date()),
      isTableShow: true,
      leftWidth: this.$leftWidth,
      rightWidth: this.$rightWidth,
      form: {},
      query: {},
      loading: false,
      page: {
        pageSize: this.$pageSize,
        currentPage: 1,
        total: 0
      },
      option: {
        menu: false,
        addBtn: false,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        dialogClickModal: false,
        column: [{}]
      },
      data: [],
      nodeId: null,
      deptInfoName: "",
      deptInfoId: "",
      pickerOption: {
        firstDayOfWeek: 1,
        disabledDate(time) {
          return time.getTime() > Date.now();
        }
      },
      defaultProps: {
        label: "title",
        value: "value",
        children: "children"
      },
      nodeList: [],
      filterText: "",
      dateFrom: dateFormat(new Date(), "yyyy-MM-dd"),
      dateTo: dateFormat(new Date(), "yyyy-MM-dd"),
      dataList: [], // 未处理的数据
      exportAllowed: true, // 禁止导出
      t2: null,
      factorList: [],
      MOTION_STATE: '运行状态'
    };
  },
  props: {
    systemId: {
      type: Number,
      default: 0
    }
  },
  computed: {
    ...mapGetters(["permission"])
  },
  watch: {

    // 开始时间
    dateFrom() {
      if (this.dateFrom) {
        let startDate = new Date(this.dateFrom);
        let endDate = new Date(this.dateTo);
        if (startDate.getTime() > endDate.getTime()) {
          this.dateTo = this.dateFrom;
        } else if (endDate.getTime() > startDate.getTime() + 7 * 24 * 60 * 60 * 1000) {
          startDate.setTime(startDate.getTime() + 7 * 24 * 60 * 60 * 1000);
          this.dateTo = dateFormat(new Date(startDate), "yyyy-MM-dd");
        }
      }
    },

    // 结束时间
    dateTo() {
      if (this.dateTo) {
        let startDate = new Date(this.dateFrom);
        let endDate = new Date(this.dateTo);
        if (startDate.getTime() > endDate.getTime()) {
          this.dateFrom = this.dateTo;
        } else if (endDate.getTime() - 7 * 24 * 60 * 60 * 1000 > startDate.getTime()) {
          endDate.setTime(endDate.getTime() - 7 * 24 * 60 * 60 * 1000);
          this.dateFrom = dateFormat(new Date(endDate), "yyyy-MM-dd");
        }
      }
    },

    // 勾选节点
    nodeList() {
      clearTimeout(this.t2);
      this.t2 = null;
      this.t2 = setTimeout(() => {
        this.onLoad(this.page);
      }, 100);
    }

  },
  methods: {
			handleExport() {
				this.$confirm("是否导出报表数据?", "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				}).then(() => {
					let time1, time2
					if(this.dateType == 0) {
						time1 = this.dateFrom + ' 00:00:00'
						time2 = this.dateTo + ' 23:59:59'
					} else {
						time1 = this.dateFrom2
						time2 = this.dateTo2
					}
					let str=`api/squirrel-loam/historyData/export?${
			        this.website.tokenHeader
			        }=${getToken()}&treeId=${this.nodeId}&start=${
			        time1
			        }&end=${time2}`
					window.open(str);
				});
			},
    // 左侧树加载事件
    ready(data) {
      this.nodeId = data.key;
      this.deptInfoName = data.title;
      this.deptInfoId = data.key;
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },

    // 日期类型更换事件
    changeDateType(val) {
      if (val > 0) {
        this.dateFrom2 = dateFormat(getPreDay(val));
        this.dateTo2 = dateFormat(new Date());
      }
    },

    // 左侧树收缩、展开
    changeTreeBox() {
      this.leftWidth = this.leftWidth == this.$leftWidth ? 0 : this.$leftWidth
      this.rightWidth = this.rightWidth == this.$rightWidth ? 24 : this.$rightWidth
    },

    // 表格导出
    excelExport() {
      xlsxDownloadExl(
        "历史数据",
        `历史数据_${this.dateFrom}-${this.dateTo}`,
        this.option.column,
        this.dataList
      );
    },

    // 搜索
    search() {
      this.page.currentPage = 1;
      this.onLoad(this.page);
    },

    // 获取表头数据
    getTableHead(nodeId) {
      let _this = this;
      return new Promise(function(resolve, reject) {
        getHead(nodeId).then(res => {
          if (res.data.success) {

            // 封装表头
            let tableHead = [{
              label: "机组名称",
              prop: "groupName",
              align: "center",
              fixed: "left",
              overHidden: true
            }, {
              label: "时间",
              prop: "collTime",
              align: "center",
              fixed: "left",
              width: 160
            }];

            // 插入除运行状态外的因子
            res.data.data.forEach(item => {
              if (item.alias !== _this.MOTION_STATE) {
                tableHead.push({
                  label: item.alias + "\n(" + item.unit + ")",
                  prop: item.alias,
                  align: _this.$tabelAlgin
                });
                _this.factorList.push(item);
              }
            });

            // 插入风机运行状态中的因子
            res.data.data.forEach(item => {
              if (item.alias === _this.MOTION_STATE) {
                // 插入运行状态
                tableHead.push({
                  label: _this.MOTION_STATE,
                  prop: "motionState",
                  align: "center",
                  children: []
                });
                item.children.forEach(childItem => {
                  tableHead.forEach(head => {
                    if (head.label === _this.MOTION_STATE) {
                      head.children.push({
                        label: `${childItem.alias}`,
                        prop: childItem.alias,
                        align: "center",
                        slot: true
                      });
                      _this.factorList.push(childItem);
                    }
                  });
                });
              }
            });

            tableHead.forEach(item => {
              if(item.label === _this.MOTION_STATE) {
                item.children = item.children.sort(_this.loamSort);
              }
            });

            // 将表头放入option
            _this.option.column = tableHead;
            resolve(res.data.data);
          } else {
            reject("网络拥堵，请退出重试");
          }
        });
      });
    },

    // 页码改变
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page);
    },

    // 每页条数改变
    sizeChange(pageSize) {
      this.page.currentPage = 1;
      this.page.pageSize = pageSize;
      this.onLoad(this.page);
    },

    // 清空搜索条件
    searchReset() {
      this.onLoad(this.page);
    },

    // 刷新页面
    refreshChange() {
      this.onLoad(this.page);
    },

    // 运行状态（风机、净化器）图标
    formatMotionHtml(value) {
      var imgSrc = "";
      if (value === "1") imgSrc = "/img/bg/normal.png";
      else if (value === "0") imgSrc = "/img/bg/offline.png";
      if (imgSrc !== "")
        return (
          '<image style="width:25px;height:25px;" src="' + imgSrc + '"></image>'
        );
      else return "-";
    },

    // 获取表格内容
    onLoad(page) {

      let time1, time2;
      if (this.dateType == 0) {
        time1 = this.dateFrom + " 00:00:00";
        time2 = this.dateTo + " 23:59:59";
      } else {
        time1 = this.dateFrom2;
        time2 = this.dateTo2;
      }
      this.getTableHead(this.deptInfoId)
        .then(resHead => {
          if (resHead.length == 0) {
            this.isTableShow = false;
            return;
          } else {
            this.isTableShow = true;
          }
          // 获取机组历史数据
          getList(this.deptInfoId,time1,time2,this.page.currentPage,page.pageSize).then(res => {
            this.dataList = [];
            res.data.data.records.forEach(item => {

              //添加分页数据 后数据结构变化
              let obj = {
                groupName: item.groupName || "-",
                collTime: item.collTime || "-"
              };

              // 根据动态表头创建因子字段 并默认初始值
              this.factorList.forEach(el => {
                obj[el.alias] = "-";
                obj[el.alias + 'isAbnormal'] = 0;
              });

              // 接口因子值
              item.factorList.forEach(el => {
                obj[el.name + 'isAbnormal'] = el.isAbnormal;
                if(el.value && el.value !== "") {
                  if(el.isAbnormal === 0)
                    obj[el.name] = this.formatFactorValue( el.value );
                  else
                    obj[el.name] = "<span style='color:red;'>" + this.formatFactorValue( el.value ) + "</span>";
                } else {
                  obj[el.name] = "-";
                }
              });

              if(obj["风机"] !== undefined)
                obj["风机"] = this.formatMotionHtml(obj["风机"]);
              if(obj["净化器"] !== undefined)
                obj["净化器"] = this.formatMotionHtml(obj["净化器"]);

              this.dataList.push(obj);
            });

            // 有数据则允许导出
            this.exportAllowed = this.dataList.length ? false : true;

            // 数据条数
            this.page.total = res.data.data.total;

            // 第一页的数据
            this.data = this.dataList
            this.loading = false;
          });
        })
        .catch(() => {
          this.loading = false;
        });
    },

    // 排序
    loamSort(ob1, ob2) {
      if (ob1.label < ob2.label) {
        return 1;
      } else if (ob1.label > ob2.label) {
        return -1;
      } else {
        return 0;
      }
    },

    // 获取因子值
    formatFactorValue(data) {
      if ((data + "").indexOf(".") < 0)
        return data;
      else {
        if((data + "").split(".")[1].length <= 3)
          return data;
        else
          return parseFloat(data).toFixed(3);
      }
    }

  }
};
</script>
<style lang="scss">


.loamHistorydataTabel {
  .el-table th>.cell {
    white-space: pre-line;
  }
}
</style>
<style lang="scss" scoped>
.map {
  width: 100%;
  height: 500px;
}

.box {
  height: 100%;
  margin-bottom: 0;
}

.el-row {
  height: calc(100% - 20px);
}

.el-col {
  height: 100%;
  overflow: auto;
}

.search-tools {
  height: 49px;
  display: flex;
  justify-content: space-between;
  padding: 0 8px;
}

.search-left {
  display: flex;
  height: 33px;
  line-height: 33px;
}

.search-right {
  display: flex;
}

.search-tabs {
  height: 33px;
  display: flex;
  align-items: center;
  margin-right: 40px;
}

</style>
